﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.ScreenShot;
using Sunny.UI;

namespace DevelopTool.Forms.ToolForms
{
    /// <summary>
    /// 截图二维码
    /// </summary>
    public partial class ScreenShotForm : BaseUIForm
    {
        private string filePath;

        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath
        {
            get
            {
                return this.filePath;
            }
            set
            {
                this.filePath = value;
            }
        }

        /// <summary>
        /// 是否启动截图
        /// </summary>
        private bool isStartScreenShot = false;

        public ScreenShotForm()
        {
            InitializeComponent();
        }


        public ScreenShotForm(bool isStartScreenShot = false)
        {
            InitializeComponent();
            this.isStartScreenShot = isStartScreenShot;
        }

        private void ScreenShotForm_Load(object sender,EventArgs e)
        {
            this.截图后始终显示到本窗口ToolStripMenuItem.Checked = Setting.ScreenShot.OnlyShowThisWindow;//从配置文件读取是否始终显示本窗口
            this.截图时显示鼠标ToolStripMenuItem.Checked = Setting.ScreenShot.ShowMouse;

            //窗口打开时启动截图
            if(this.isStartScreenShot)
            {
                this.OpenScreenShot(false);
            }

            ThemHelper.SetSystemThem(this);

            UIMenuStyle uIMenuStyle = Setting.Theme.ControlThemColor;
            switch(uIMenuStyle)
            {
                case UIMenuStyle.Black:
                    imageView.BackColor = ThemHelper.CustomBackColor_Black;
                    break;
                case UIMenuStyle.White:
                    imageView.BackColor = ThemHelper.CustomBackColor_White;

                    break;
            }
            

            this.ScreenShot.Text = $"截图({HotKeyHelper.GetWinfromHotKeyIntoShow(Setting.ScreenShot.HotKey)})";


            if(!string.IsNullOrEmpty(this.filePath) && File.Exists(this.filePath))
            {
                this.imageView.Image = ImageEx.FromFile(this.filePath);
                this.codeEditorControl.ClearContent();
            }
            

        }


        /// <summary>
        /// 截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScreenShot_Click(object sender,EventArgs e)
        {
            this.OpenScreenShot(true);
        }

        /// <summary>
        /// 打开截图窗口（开始截图）
        /// </summary>
        /// <param name="formThis">是否从本窗体启动的</param>
        /// <returns></returns>
        private void OpenScreenShot(bool formThis)
        {
            try
            {
                this.Hide();//截图前隐藏本窗口

                //截图
                FrmCapture frmCapture = new FrmCapture(this.截图时显示鼠标ToolStripMenuItem.Checked,false)
                {
                    TopMost = true//截图窗口置顶
                };
                var dialogResult = frmCapture.ShowDialog();//打开截图窗口

                if(formThis)
                {
                    this.Show();//如果截图调用来自本窗口，而不是快捷键的话，始终还原显示本窗口
                }
                else
                {
                    if(dialogResult == DialogResult.Cancel)
                        this.Close();
                }

                if(dialogResult != DialogResult.OK) return;

                //本窗口显示逻辑
                if((formThis || this.截图后始终显示到本窗口ToolStripMenuItem.Checked) && frmCapture.ConfirmType == 1 && frmCapture.CaptureImage != null)//来自本窗口的截图调用
                {
                    this.imageView.Image = frmCapture.CaptureImage;//截图返回的图片
                    this.codeEditorControl.ClearContent();
                }
                else if(frmCapture.ConfirmType == 5 && frmCapture.CaptureImage != null)//来自快捷键的截图调用
                {
                    this.Show();
                    this.imageView.Image = frmCapture.CaptureImage;//截图返回的图片
                    this.DecodeQrCode(this.imageView.Image);

                }
                else if(!formThis)
                {
                    this.Close();
                }

            }
            catch(Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
            }
        }


        /// <summary>
        /// 识别二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDecodeQrCode_Click(object sender,EventArgs e)
        {
            if(this.imageView.Image == null)
            {
                this.ShowWarningTip(this.btnDecodeQrCode,"请先【打开图片】或【截图】~");
                return;
            }

            DecodeQrCode(this.imageView.Image);
        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEncodeQrCode_Click(object sender,EventArgs e)
        {
            if(string.IsNullOrEmpty(this.codeEditorControl.ContentText))
            {
                this.ShowWarningTip(this.btnDecodeQrCode,"请在下方【文本编辑器】中输入二维码内容~");
                return;
            }

            imageView.Image = QrCodeHelper.GenerateQrCode(this.codeEditorControl.ContentText);
        }


        private void DecodeQrCode(Image image)
        {
            if(image == null) return;

            try
            {
                string text = QrCodeHelper.DecodeQrCode(new Bitmap(image));

                if(!string.IsNullOrEmpty(text))
                {
                    this.codeEditorControl.ClearContent();//清空编辑器内容

                    this.codeEditorControl.ContentText = text;
                }
                else
                {
                    this.ShowWarningDialog("未能识别到二维码");
                }
            }
            catch(Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
            }
        }


        private void 打开图片ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string fileName = string.Empty;
            if(!Dialogs.OpenFileDialog(ref fileName, Common.ImageHelper.GetImageFilter())) return;

            try
            {
                this.imageView.Image = ImageEx.FromFile(fileName);
                this.codeEditorControl.ClearContent();
            }
            catch(Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
            }
        }


        private void 图片另存为ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(this.imageView.Image == null)
            {
                this.ShowWarningTip(this.图片另存为ToolStripMenuItem,"没有需要保存的图片~");
                return;
            }
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Filter = Common.ImageHelper.GetImageFilter(),
                    FileName = "DevelopTool_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png"
                };
                if(saveFileDialog.ShowDialog() != DialogResult.OK) return;

                //这句很重要，不然不能正确保存图片或出错（关键就这一句）
                Bitmap bmp = new Bitmap(imageView.Image);
                //保存到磁盘文件
                bmp.Save(saveFileDialog.FileName,imageView.Image.RawFormat);

                this.ShowSuccessNotifier("图片已保存到:" + saveFileDialog.FileName);
            }
            catch(Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
            }
        }

        private void 截图后始终显示到本窗口ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            this.截图后始终显示到本窗口ToolStripMenuItem.Checked = !this.截图后始终显示到本窗口ToolStripMenuItem.Checked;
            Setting.ScreenShot.OnlyShowThisWindow = this.截图后始终显示到本窗口ToolStripMenuItem.Checked;
        }

        private void 截图时显示鼠标ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            this.截图时显示鼠标ToolStripMenuItem.Checked = !this.截图时显示鼠标ToolStripMenuItem.Checked;
            Setting.ScreenShot.ShowMouse = this.截图时显示鼠标ToolStripMenuItem.Checked;
        }

    }
}
